package com.xiaodong.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.xiaodong.reggie.currency.BaseContest;
import com.xiaodong.reggie.currency.R;
import com.xiaodong.reggie.entity.AddressBook;
import com.xiaodong.reggie.service.AddressBookService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@RestController
@RequestMapping("/addressBook")
public class AddressBookContorller {

    @Autowired
    private AddressBookService addressBookService;

    //查询所有地址
    @GetMapping("/list")
    public R<List<AddressBook>> list() {

        LambdaQueryWrapper<AddressBook> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.eq(AddressBook::getUserId, BaseContest.getId());

        List<AddressBook> list = addressBookService.list(queryWrapper);

        return R.success(list);
    }

    //添加地址
    @PostMapping
    public R<String> save(@RequestBody AddressBook addressBook) {

        //log.info("地址管理=={}",addressBook.getConsignee());
        addressBook.setUserId(BaseContest.getId());

        addressBookService.save(addressBook);

        return R.success("地址添加成功");

    }

    //修改默认值
    @PutMapping("/default")
    public R<AddressBook> update(@RequestBody AddressBook addressBook) {

        //将该账号的是否默认全部改为不是
        LambdaUpdateWrapper<AddressBook> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(AddressBook::getUserId, BaseContest.getId());
        log.info("本用户的id=={}", BaseContest.getId());
        updateWrapper.set(AddressBook::getIsDefault, 0);
        addressBookService.update(updateWrapper);

        //根据id修改默认值
        addressBook.setIsDefault(1);
        addressBookService.updateById(addressBook);

        return R.success(addressBook);
    }

    //根据id查询地址
    @GetMapping("/{id}")
    public R<AddressBook> get(@PathVariable Long id) {

        AddressBook byId = addressBookService.getById(id);
        if (byId != null) {
            return R.success(byId);
        }

        return R.error("没有发现该对象");
    }

    //查询默认地址
    @GetMapping("/default")
    public R<AddressBook> getDefault() {

        LambdaQueryWrapper<AddressBook> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AddressBook::getUserId, BaseContest.getId());
        queryWrapper.eq(AddressBook::getIsDefault, 1);
        AddressBook one = addressBookService.getOne(queryWrapper);

        if (one != null) {
            return R.success(one);
        }
        return R.error("没有默认地址");

    }

    //修改内容
    @PutMapping
    public R<String> updateByDefault(@RequestBody AddressBook addressBook){

        addressBookService.updateById(addressBook);

        return R.success("修改成功");

    }
}
